package com.lifeng.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Created by lifeng on 2019/10/30.
 * 请求花费时间过滤器
 */
public class RequestCostTimesFilter implements GlobalFilter, Ordered {
    private static Logger logger = LoggerFactory.getLogger(RequestCostTimesFilter.class );

    @Override
    public Mono<Void> filter(ServerWebExchange serverWebExchange, GatewayFilterChain gatewayFilterChain) {
        //serverWebExchange.getRequest();//可以获取原始的httprequest对象,可以加工处理request里的任何信息
        serverWebExchange.getAttributes().put("reqBeginTimes",System.currentTimeMillis());
        Mono<Void> mono = gatewayFilterChain.filter(serverWebExchange).then(
                Mono.fromRunnable(() -> {
                    Long reqBeginTimes = serverWebExchange.getAttribute("reqBeginTimes");
                    if (reqBeginTimes != null) {
                        StringBuilder sb = new StringBuilder(serverWebExchange.getRequest().getURI().getRawPath())
                                .append(":")
                                .append(System.currentTimeMillis() - reqBeginTimes)
                                .append("ms");
                        logger.info("耗时:"+sb.toString());
                    }
                })
        );
        return mono;
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
